<template>
  <div class="content">
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>图片</th>
          <th>商品</th>
          <th>价格</th>
          <th>库存</th>
          <th>购买数量</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td>{{ item.id }}</td>
          <td>
            <img :src="item.image" alt="商品图片" width="50" />
          </td>
          <td>{{ item.title }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.count }}</td>
          <td>1</td>
        </tr>
      </tbody>
    </table>
    <p>总价: {{ totalSumPrice.toFixed(2) }}</p>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';

// 购物车数据
const tableData = ref([]);

// 请求购物车
const queryCarts = async () => {

    // 通过网络请求调用购物车接口
    const response = await fetch('http://localhost:3000/books');
    const data = await response.json();
    tableData.value = data;
  } 

// 计算总价
// 计算总价
const totalSumPrice = computed(() => {
  return tableData.value.reduce((sum, item) => {
    // 使用Number()将item.price转换为数字类型
    const price = Number(item.price); 
    return sum + (isNaN(price)? 0 : price * 1);
  }, 0);
});

// 组件挂载后调用请求方法
onMounted(() => {
  queryCarts();
});
</script>

<style scoped>
.content {
  width: 100%;
  padding: 20px;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: center;
}

th {
  background-color: #f0f0f0;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

img {
  display: block;
  margin: 0 auto;
}
</style>